import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.prototype.$http = axios
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputValue: '',
    // 下一个id
    nextId: 5,
    // 定义任务的状态 已完成 未完成 全部
    taskType: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    // 为 store 中的inputValue 赋值
    setInputValue(state, value) {
      state.inputValue = value
    },
    // 添加列表项
    addItem(state) {
      const taskObj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(taskObj)
      state.nextId++
      state.inputValue = ''
    },
    // 根据id删除对应的任务
    removeItem(state, id) {
      state.list.splice(id, 1)
    },
    // 修改任务列表中的状态
    changeStatus(state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.status
      }
    },
    // 清除已经完成的任务
    cleanItem(state) {
      state.list = state.list.filter(x => x.done === false)
    },
    // 修改任务的状态 all undone done
    changeTaskType(state, type) {
      state.taskType = type
    }
  },
  actions: {
    getList(context) {
      axios.get('list.json').then(({
        data
      }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    infoList(state) {
      if (state.taskType === 'all') {
        return state.list
      }
      if (state.taskType === 'undone') {
        return state.list.filter(x => !x.done)
      }
      if (state.taskType === 'done') {
        return state.list.filter(x => x.done)
      }
      return state.list
    },
    // 统计未完成的任务的条数
    unDoneTask(state) {
      return state.list.filter(x => x.done === false).length
    }
  },
  modules: {}
})
